<!--suppress HtmlDeprecatedAttribute -->
<template>
  <div>
    <logistics-dialog v-model="logisticsVisible" :order-id="logisticsOrderId"/>
    <el-table :data='orderDataTrue' ref="order" style="width: 100%" min-height="600"
      v-loading='paginationDisabled' element-loading-text='拼命加载中'
      element-loading-spinner='el-icon-loading' element-loading-background='rgba(255, 255, 255, 0.4)'>
      <el-table-column prop="id" label="编号" align="center" width="70px"/>
      <el-table-column label="名称" align="center" width="340px">
        <template slot-scope="scope">
          <good-box-simple v-bind="scope.row['goodDetail']" :width-size="0.9" :height-size="0.9"/>
        </template>
      </el-table-column>
      <el-table-column prop="price" label="金额" align="center"/>
      <el-table-column prop='createTime' label="创建时间" align="center" min-width="120px"/>
      <el-table-column prop="state" label="状态" align="center"/>
      <el-table-column prop="action" label="操作" fixed="right" align="center">
        <template slot-scope="scope">
          <el-dropdown trigger="click">
            <el-button type="primary" size="mini" :loading="loading">
              操作<i class="el-icon-arrow-down el-icon--right"/>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <order-item-menu :row="scope.row" @change="freshTable" @click="itemClick">
                <el-dropdown-item>
                  <el-button type="text" @click="fnViewDetails(scope.row)">订单详情</el-button>
                </el-dropdown-item>
              </order-item-menu>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination class="pagination" @size-change="handleSizeChange" @current-change='handleCurrentChange'
      :page-size.sync='size' :total.sync="total" :current-page.sync="page" background :disabled="paginationDisabled"
      layout="sizes, total, jumper, prev, pager, next" />
  </div>
</template>

<script>
import { queryOrderDetailPageWrapper } from '@/api/ApiOrderDetail'
import PageDTO from '@/api/entity/PageDTO'
import OrderDetailQueryDTO from '@/api/entity/OrderDetailQueryDTO'
import { ResultCode } from '@/constants/constants'
import { convertDetailToSimpleGoodItem, formatTime } from '@utils/DataConvertUtils'
import GoodBoxSimple from '@/components/general/goods/GoodBoxSimple'
import { queryGoodDetailById } from '@/api/ApiGoodDetail'
import OrderItemMenu from '@/views/part/account/part/accountOrder/OrderItemMenu'
import LogisticsDialog from '@/views/part/account/part/accountOrder/LogisticsDialog'

export default {
  name: 'AccountOrder',
  components: { LogisticsDialog, OrderItemMenu, GoodBoxSimple },
  data () {
    return {
      queryOrderLoading: false,
      queryGoodLoading: false,
      logisticsVisible: false,
      logisticsOrderId: 0,
      total: 0,
      size: 10,
      page: 1,
      orderData: [],
      goodDetail: []
    }
  },
  computed: {
    loading () {
      return this.queryGoodLoading || this.queryOrderLoading
    },
    paginationDisabled () {
      return this.loading
    },
    orderDataTrue () {
      const list = []
      if (this.orderData && typeof this.orderData === 'object') {
        this.orderData.forEach(item => {
          const id = item.goodId
          for (let i = 0; i < this.goodDetail.length; i++) {
            if (this.goodDetail[i].id === id) {
              item['goodDetail'] = this.goodDetail[i]
              break
            }
          }
          list.push(item)
        })
      }
      return list
    }
  },
  methods: {
    /**
     * 查看订单详情，任何时候都可以调用
     * @param row 订单详细数据
     */
    fnViewDetails (row) {
      this.$message.success(row.id + '')
    },
    handleSizeChange () {
      this.page = 1
      this.freshTable()
    },
    handleCurrentChange () {
      this.freshTable()
    },
    convertOrderDetail (item) {
      item.createTime = formatTime(item.createTime)
      const list = item['list']
      if (list && typeof list === 'object') {
        item.name = list[0]['goodName']
      }
      item['goodId'] = item['list'][0].goodId
      return item
    },
    freshTable () {
      this.queryOrderLoading = true
      this.queryGoodLoading = true
      const pageDTO = PageDTO.instance()
      pageDTO.setSize(this.size)
      pageDTO.setCurrent(this.page)
      const wrapper = OrderDetailQueryDTO.instance()
      wrapper.addOrderDesc('createTime')
      pageDTO.setCondition(wrapper)
      queryOrderDetailPageWrapper(pageDTO, data => {
        if (data && data.code === ResultCode.OK) {
          const orderData = data.object['records']
          const list = []
          orderData.forEach(item => {
            list.push(this.convertOrderDetail(item))
          })
          const queryDetailIds = []
          list.forEach(item => {
            if (item && item.list && typeof item.list === 'object') {
              item.list.forEach(item2 => {
                queryDetailIds.push(item2.goodId)
              })
            }
          })
          const queryDetail = []
          let i, j
          for (i = 0; i < queryDetailIds.length; i++) {
            const item = queryDetailIds[i]
            for (j = 0; j < this.goodDetail.length; j++) {
              const item2 = this.goodDetail[j]
              if (item === item2.id) {
                break
              }
            }
            if (j < this.goodDetail.length) {
              // 存在
              continue
            }
            for (j = i + 1; j < queryDetailIds.length; j++) {
              const item2 = queryDetailIds[i]
              if (item === item2) {
                break
              }
            }
            if (j < queryDetailIds.length) {
              // 存在
              continue
            }
            queryDetail.push(queryGoodDetailById(item, (data) => {
              if (data && data.code === ResultCode.OK) {
                data = data.object
                data = convertDetailToSimpleGoodItem(data)
                this.goodDetail.push(data)
              }
            }))
          }
          if (queryDetail.length > 0) {
            Promise.all(queryDetail).then(() => {
              this.orderData = list
              this.total = data.object['total']
              this.queryGoodLoading = false
            })
          } else {
            this.orderData = list
            this.total = data.object['total']
            this.queryGoodLoading = false
          }
        }
      }, () => {
        this.queryOrderLoading = false
      })
    },
    itemClick (common, row) {
      if (!row || !row.id) {
        return
      }
      switch (common) {
        // 订单评论
        case 'review':
          // todo 评论
          this.$message.success('订单评论：' + row.id)
          break
        // 查看物流
        case 'trance':
          this.logisticsOrderId = row.id
          this.logisticsVisible = true
          break
      }
    }
  },
  mounted () {
    this.freshTable()
  }
}
</script>

<style lang="scss" scoped>
  .pagination{
    margin-top: 20px;
  }
</style>
